import {
  mainApiDomain
} from '../config';
// import signApiService from '../services/sign-api';

const appData = getApp();
console.log(appData)
const showLoading = () => {
  wx.showNavigationBarLoading();
};
const hideLoading = () => {
  wx.hideNavigationBarLoading();
};

const trim = (str) => {
  return str.replace(/(^\s*)|(\s*$)/g, '');
};

const handleParams = (data) => {
  for (let key of Object.keys(data || {})) {
    data[key] = typeof data[key] === 'string' ? trim(data[key]) : data[key];
    data[key] !== false && data[key] !== 0 && data[key] !== '' &&  !data[key]  && delete data[key];
  }
};

class Request {
  requestMainApi(url, method, data = {}, header = {}) {
    handleParams(data);
    showLoading();
    const wxToken = wx.getStorageSync('apiAccessToken')
    appData.userInfo ? appData.userInfo['apiAccessToken'] : '';
    // const {
    //   timestamp,
    //   nonce,
    //   signature
    // } = signApiService.apiSign();
    header['wx-token'] = wxToken ? wxToken : '';
    // header['timestamp'] = timestamp;
    // header['nonce'] = nonce;
    // header['signature'] = signature;

    return new Promise((resolve, reject) => {
      wx.request({
        method,
        header,
        timeout: 5000,
        url: `${mainApiDomain}${url}`,
        data: Object.assign(data),
        success(res) {
          const passCode = [200]
          if (passCode.includes(res.data.code)) {
            resolve(res.data.data);
          } else {
            setTimeout(() => {
              wx.showToast({
                title: res.data.message,
                icon: 'none'
              })
            }, 1000);
            //返回首页状态码
            if ([302, 703, 307, 1604].includes(res.data.code)) {
              wx.setStorageSync('apiAccessToken', '')
              appData.apiAccessToken = ''
              const pages = getCurrentPages();
              const currentPage = pages[pages.length - 1].route;
              if (!currentPage.includes('login/login')) {
                appData.backUrl = null
                wx.reLaunch({
                  url: '/pages/home/home',
                });
              }

              // const pages = getCurrentPages();
              // const currentPage = pages[pages.length - 1].route;
              // if(!currentPage.includes('index/index')) {
              //   checkLogin(resolve, reject, header, res);
              // }
            } else {
              reject(res.data);
            }
          }
        },
        fail(res) {
          reject(res)
          wx.showToast({
            title: '服务器异常',
            icon: 'none'
          })
        },
        complete(res) {
          hideLoading()
        }
      })
    });

    function checkLogin(resolve, reject, header, res) {
      wx.login({
        timeout: 2000,
        success: ({
          code
        }) => {
          wx.request({
            method: 'POST',
            header,
            url: `${mainApiDomain}/v1/customer/login`,
            data: Object.assign({
              code
            }),
            success(userRes) {
              if (userRes.data.code === 0) {
                let isUserAuthed = userRes.data.data.isRegistered;
                let isCancelUser = userRes.data.data.deactivated;

                if (isUserAuthed && !isCancelUser) {
                  reject();
                  wx.showModal({
                    title: '提示',
                    content: '您当前的授权已过期，\n请点击确认，一键再次授权\n登录哦～',
                    showCancel: false,
                    success: function (res) {
                      if (res.confirm) {
                        wx.reLaunch({
                          url: '/pages/index/index'
                        });
                      }
                    }
                  });
                } else if (isUserAuthed && isCancelUser) {
                  const pages = getCurrentPages();
                  const currentPage = pages[pages.length - 1].route;
                  if (currentPage.includes('coupon/coupon') || currentPage.includes('profile/profile') || currentPage.includes('cart/cart') || currentPage.includes('member-code/member-code')) {
                    reject(res.data);
                  } else if (currentPage.includes('index/index')) {
                    wx.switchTab({
                      url: '/pages/homepage/homepage',
                    });
                  } else {
                    reject(res.data);
                    wx.showModal({
                      title: '提示',
                      content: '您当前的授权已过期，\n请点击确认，一键再次授权\n登录哦～',
                      showCancel: false,
                      success: function (res) {
                        if (res.confirm) {
                          wx.navigateTo({
                            url: `/pages/login/login?isCancelUser=true`
                          });
                        }
                      }
                    });
                  }
                } else {
                  reject(res.data);
                }
              }
            }
          });
        },
        fail: () => { }
      });
    }
  }
  uploadFile(url, data = {}, header = {}) {
    const userToken = appData.userInfo ? appData.userInfo['apiAccessToken'] : '';
    // const {
    //   timestamp,
    //   nonce,
    //   signature
    // } = signApiService.apiSign();
    header['api-access-token'] = userToken ? userToken : '';
    // header['timestamp'] = timestamp;
    // header['nonce'] = nonce;
    // header['signature'] = signature;
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: `${mainApiDomain}${url}`,
        header,
        timeout: 3000,
        filePath: data.path,
        name: data.name,
        success(res) {
          if (res.statusCode === 413) {
            return reject(res);
          }
          const response = JSON.parse(res.data);
          if (response.code === 0) {
            resolve(response.data);
          } else {
            reject(response);
          }
        },
        fail(res) {
          reject(res)
        },
        complete(res) {
          // console.log(res);
        }
      })
    })
  }
}

export default new Request();